<script setup>
import { ArrowRight } from "@element-plus/icons-vue";
import { accLogin, getSmsCode, resetPwd, smsLogin } from "@/api/user";
import { useUser } from "@/store/useUser";
import { useRouter } from "vue-router";
import { ref, watch, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getProtocol } from "@/api/base";
import { encrypt } from "@/utils/func";
import { useSocketStore } from "@/store/useSocketStore";

const router = useRouter();
const checked = ref(true);
const tabActive = ref(0);
const socketStore = useSocketStore();
const reserPwdStatus = ref(false);
const tapTabActive = (index) => {
  tabActive.value = index;
};
const socket = computed(() => socketStore.socket);
// 发送验证码
const sendStatus = ref(false);
const snedTime = ref(60);
const mobile = ref("");
const smsCode = ref("");
const timer = ref();
const sendSms = async () => {
  if (!mobile.value) {
    return ElMessage.warning("请输入手机号");
  }
  if (sendStatus.value || snedTime.value !== 60) return;
  sendStatus.value = true;
  try {
    const sendSmsParams = {
      mobile: mobile.value,
    };
    if (reserPwdStatus.value) {
      sendSmsParams.type = 3;
    }
    const data = await getSmsCode(sendSmsParams);
    if (data.code === 200) {
      ElMessage.success("发送成功");
    }
    timer.value = setInterval(() => {
      snedTime.value--;
      if (snedTime.value === 0) {
        sendStatus.value = false;
        snedTime.value = 60;
        clearInterval(timer.value);
      }
    }, 1000);
  } catch (e) {
    sendStatus.value = false;
    console.log("error msg:", e.message);
  }
};
// 登录
const password = ref("");
const loginStatus = ref(false);
const login = async () => {
  if (loginStatus.value) return;
  const user = useUser();
  if (tabActive.value === 0) {
    // 短信登录
    if (!mobile.value) {
      return ElMessage.warning("请输入手机号");
    }
    if (!smsCode.value) {
      return ElMessage.warning("请输入短信验证码");
    }
    if (!checked.value) {
      return ElMessage.warning("请勾选同意协议");
    }
    loginStatus.value = true;
    try {
      const { data } = await smsLogin({
        mobile: mobile.value,
        code: smsCode.value,
        userType: 2,
      });
      console.log(data);
      if (data.access_token) {
        ElMessage.success("登录成功");
        await user.setToken(data.access_token);
        // 延迟1秒
        await new Promise((resolve) => setTimeout(resolve, 1000));
        await user.userInfoAction();
        if (user.getUserInfo && user.getUserInfo.userId) {
          if (user.getUserInfo.infoUpdate === 1 && user.getUserInfo.isAuth === 1) {
            await router.push("/");
          } else {
            await router.push("/editUser");
          }
        }
      }
    } catch (e) {
      console.log("error msg:", e);
      ElMessage.error("登录失败");
    } finally {
      loginStatus.value = false;
    }
  }
  if (tabActive.value === 1) {
    // 账号密码登录
    if (!mobile.value) {
      return ElMessage.warning("请输入手机号");
    }
    if (!password.value) {
      return ElMessage.warning("请输入密码");
    }
    if (!checked.value) {
      return ElMessage.warning("请勾选同意协议");
    }
    loginStatus.value = true;
    try {
      const encryptData = encrypt({
        username: mobile.value,
        password: password.value,
      });
      const { data } = await accLogin({
        username: encryptData.username,
        password: encryptData.password,
        userType: 2,
      });
      if (!data || !data.access_token) {
        ElMessage.error("登录失败");
        return;
      }
      ElMessage.success("登录成功");
      await user.setToken(data.access_token);
      // 延迟1秒
      await new Promise((resolve) => setTimeout(resolve, 1000));
      await user.userInfoAction();
      if (user.getUserInfo && user.getUserInfo.userId) {
        await router.push("/");
      }
    } catch (e) {
      console.log("error msg:", e);
    } finally {
      loginStatus.value = false;
    }
  }
};
// 找回密码
const resetPwdFN = async () => {
  if (!mobile.value) {
    return ElMessage.warning("请输入手机号");
  }
  if (!smsCode.value) {
    return ElMessage.warning("请输入短信验证码");
  }
  if (!password.value) {
    return ElMessage.warning("请输入新密码");
  }
  loginStatus.value = true;
  try {
    const data = await resetPwd({
      mobile: mobile.value,
      smsCode: smsCode.value,
      password: password.value,
    });
    ElMessage.success("找回密码成功");
    reserPwdStatus.value = false;
  } catch (e) {
    console.log("error msg:", e);
  } finally {
    loginStatus.value = false;
  }
};
watch(reserPwdStatus, () => {
  mobile.value = "";
  smsCode.value = "";
  password.value = "";
});
// 获取协议
const protocol = ref([]);
const getProtocolFN = async () => {
  const data = await getProtocol();
  protocol.value = data.data;
};
getProtocolFN();
const agreementList = computed(() => {
  return protocol.value.filter(
    (item) => item.type === 1 || item.type === 2 || item.type === 3 || item.type === 4
  );
});

onMounted(() => {
  socket.value?.disconnect();
});
</script>

<template>
  <div class="login-view">
    <div class="login-form">
      <img class="form-title" src="@/assets/login-form-title.png" alt="" />
      <template v-if="!reserPwdStatus">
        <div class="login-form-content">
          <div class="form-left">
            <img class="logo" src="@/assets/web-logo-1.png" alt="" />
            <p class="tips">打开技能猴子App扫一扫即可登录</p>
            <div class="qr">
              <img src="@/assets/cs-qrcode-img.png" alt="" />
            </div>
            <router-link class="app-link" to="/appDownload"
              >还没有技能猴子App？点击去下载</router-link
            >
          </div>
          <div class="form-right">
            <p class="login-tab">
              <span :class="{ active: tabActive === 0 }" @click="tapTabActive(0)"
                >手机号登录</span
              >
              <span :class="{ active: tabActive === 1 }" @click="tapTabActive(1)"
                >密码登录</span
              >
            </p>
            <div class="form-item">
              <img src="@/assets/phone-icon.png" alt="" />
              <input v-model="mobile" type="number" placeholder="请输入手机号" />
            </div>
            <template v-if="tabActive === 0">
              <div class="form-item">
                <img src="@/assets/sms-icon.png" alt="" />
                <input type="number" v-model="smsCode" placeholder="请输入短信验证码" />
                <span @click="sendSms">{{
                  sendStatus ? `${snedTime} S` : "发送验证码"
                }}</span>
              </div>
            </template>
            <template v-if="tabActive === 1">
              <div class="form-item">
                <img src="@/assets/sms-icon.png" alt="" />
                <input v-model="password" type="password" placeholder="请输入密码" />
              </div>
              <p class="forgot-password" @click="reserPwdStatus = true">忘记密码？</p>
            </template>
            <el-button
              class="submit-btn"
              @click="login"
              color="#1dbf73"
              style="color: #fff !important"
              :loading="loginStatus"
              :disabled="loginStatus"
              >登录</el-button
            >
            <p class="agreement">
              <el-checkbox v-model="checked" />&nbsp; 我已阅读并同意&nbsp;<router-link
                style="margin-right: 4px"
                v-for="item in agreementList"
                :to="`/agreement?id=${item.id}`"
                :key="item.id"
                target="_blank"
                >{{ item.title }}</router-link
              >
            </p>
            <a class="to-seller" href="http://jinenghouzi.com/" target="_blank"
              >买家登录 <el-icon class="icon"><ArrowRight /></el-icon
            ></a>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="reset-form-content">
          <img
            class="modal-close"
            @click="reserPwdStatus = false"
            src="@/assets/modal-close.png"
            alt=""
          />
          <p class="modal-title">
            <img
              src="@/assets/modal-back.png"
              alt=""
              @click="reserPwdStatus = false"
            /><span>找回密码</span>
          </p>
          <div class="form">
            <div class="form-item" style="width: 296px">
              <img src="@/assets/phone-icon.png" alt="" />
              <input v-model="mobile" type="text" placeholder="请输入手机号" />
            </div>
            <div class="form-item" style="width: 296px">
              <img src="@/assets/sms-icon.png" alt="" />
              <input type="text" v-model="smsCode" placeholder="请输入短信验证码" />
              <span @click="sendSms">{{
                sendStatus ? `${snedTime} S` : "发送验证码"
              }}</span>
            </div>
            <div class="form-item" style="width: 296px">
              <img src="@/assets/pwd-icon.png" alt="" />
              <input type="password" v-model="password" placeholder="请输入新密码" />
            </div>
            <el-button class="submit-btn" style="margin-top: 24px" @click="resetPwdFN"
              >找回密码</el-button
            >
            <p class="to-login" @click="reserPwdStatus = false">直接登录</p>
          </div>
        </div>
      </template>
    </div>
    <div class="web-footer">
      <p>有声探网络科技有限公司  |  中国(合肥)高新区望江西路888号</p>
      <p>©2022 备案号：皖ICP备17049047号-6沪公网安备 31010502005484号</p>
    </div>
  </div>
  <div class="one-msg" v-if="false">
    <div class="msg-content">
      <h4 class="title">致技能猴子卖家的一封信</h4>
      <h4 class="title-sub">尊敬的技能猴子卖家您好：</h4>
      <p class="p-1">
        技能猴子共有两种个体：经营技能店铺的超级个体和上传并投递简历的远程个体。前者要求缴纳店铺保证金，可以直接与平台客户接触；后者无需缴纳保证金，由平台自营统一安排与客户的面试和服务交易。根据过往的治理经验，如果您是想成为超级个体经营技能店铺，我们认为有以下情况的卖家不适合入驻。为了避免今后与买家或平台发生一些不愉快的事情，请认真阅读和审度是否要继续入驻：
      </p>
      <p class="p-1">
        <b>1.特别惧怕吃亏的：</b
        >稍微感受到一点吃亏就浑身不舒服，自己控制不住的难受，甚至还会升级矛盾的。误会总是会在一方以为自己吃亏的情况下发生，而对吃小亏有容忍度的人总是能消除很多不必要的误会。如果您对吃亏真的十分敏感，我们认可您性格的合理性，但您确实不适合加入技能猴子卖家。<br />
        <b> 2.下意识负能量的：</b
        >一旦买家表达出轻微的负能量，自己便用更负的能量回应的。正确的样子是我们永远是正能量的，面对不讲道理的买家，避开不服务即可，情节恶劣的可以举报。如果您做不到这一点，说明你还是更合适上班挣钱的模式，技能猴子卖家是经商模式，只有自己始终保持正能量，客户才会感觉到和你合作的愉悦感。<br />
        <b>3.碰运气或內卷的：</b
        >想着来平台碰碰运气，或者走低价路线内卷引流的。技能猴子的目标是让远程人才真正能在平台以此为生，抱着内卷、养鱼心态的平台拒绝您的加入。一经发现，账户余额和保证金全扣，身份证号和对应账号永久拉黑封号。
      </p>
      <p class="btns">
        <el-button class="cancel">再考虑考虑</el-button>
        <el-button class="agree">我已认真阅读并同意</el-button>
      </p>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login-view {
  padding-top: 80px;
  height: 100vh;
  box-sizing: border-box;
  background: url("~/assets/login-bg.png") no-repeat;
  background-size: cover;
}
.login-form {
  width: 800px;
  margin: 0 auto;
  padding-top: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.form-title {
  width: 400px;
  margin-bottom: 48px;
}
.login-form-content {
  background: #ffffff;
  border-radius: 16px 16px 16px 16px;
  width: 100%;
  display: flex;
}
.reset-form-content {
  background: #ffffff;
  border-radius: 16px 16px 16px 16px;
  width: 380px;
  display: flex;
  position: relative;
  padding: 42px 42px 0;
  flex-direction: column;
  box-sizing: border-box;
}
.form-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 46px 0;
  border-right: 1px solid rgba(25, 30, 40, 0.12);
  .logo {
    width: 118px;
    margin-bottom: 32px;
  }
  .tips {
    color: #191e28;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
  }
  .qr {
    box-shadow: 0px 4px 24px 0px rgba(3, 10, 26, 0.06);
    border-radius: 12px 12px 12px 12px;
    border: 1px solid #edeff4;
    background: #ffffff;
    width: 160px;
    height: 160px;
    margin-bottom: 24px;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .app-link {
    color: #01977f;
    text-decoration: none;
  }
}
.form-right {
  flex: 1;
  padding-top: 48px;
  display: flex;
  align-items: center;
  flex-direction: column;
}
.login-tab {
  margin-bottom: 34px;
  span {
    color: rgba(25, 30, 40, 0.36);
    font-size: 16px;
    cursor: pointer;
    &:first-child {
      margin-right: 50px;
    }
    &.active {
      color: #191e28;
      position: relative;
      &::after {
        content: "";
        position: absolute;
        bottom: -8px;
        left: 50%;
        width: 48px;
        height: 2px;
        margin-left: -24px;
        background: #01977f;
      }
    }
  }
}
.form-item {
  display: flex;
  align-items: center;
  border-radius: 8px 8px 8px 8px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  width: 304px;
  height: 48px;
  margin-bottom: 16px;
  padding: 0 12px;
  box-sizing: border-box;
  img {
    width: 18px;
    height: 18px;
  }
  input {
    flex: 1;
    height: 100%;
    border: none;
    outline: none;
    user-select: none;
    padding-left: 12px;
  }
  span {
    color: #1dbf73;
    cursor: pointer;
  }
}
.forgot-password {
  color: #1dbf73;
  text-align: right;
  width: 100%;
  padding-right: 48px;
  box-sizing: border-box;
  margin: -10px 0 -6px 0;
  cursor: pointer;
}
.submit-btn {
  width: 304px;
  height: 48px;
  background: #1dbf73;
  border-radius: 8px 8px 8px 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  margin-top: 16px;
  cursor: pointer;
}
.agreement {
  margin-top: 8px;
  font-size: 12px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  color: rgba(25, 30, 40, 0.32);
  a {
    text-decoration: none;
    color: rgba(29, 191, 115, 1);
  }
}
.to-seller {
  color: #019a81;
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  text-decoration: none;
  .icon {
    position: relative;
    top: 1px;
  }
}
.modal-close {
  position: absolute;
  top: 40px;
  right: 40px;
  width: 16px;
  height: 16px;
  cursor: pointer;
}
.modal-title {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  img {
    width: 20px;
    height: 20px;
    margin-right: 4px;
    cursor: pointer;
  }
  span {
    color: #191e28;
    font-size: 18px;
    font-weight: bold;
  }
}
.to-login {
  text-align: center;
  color: #019a81;
  padding: 24px 0;
  cursor: pointer;
}
.web-footer {
  position: absolute;
  bottom: 48px;
  left: 0;
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: rgba(25, 30, 40, 0.36);
  p:nth-child(1) {
    margin-bottom: 10px;
  }
}
.one-msg {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
  .msg-content {
    background: #ffffff;
    border-radius: 12px 12px 12px 12px;
    padding: 32px;
    max-width: 900px;
  }
  .title {
    color: #191e28;
    font-size: 20px;
    width: 100%;
    text-align: center;
    margin-bottom: 26px;
  }
  .title-sub {
    font-size: 16px;
    color: #191e28;
    margin-bottom: 16px;
  }
  p {
    color: rgba(25, 30, 40, 0.84);
    line-height: 28px;
    margin-bottom: 8px;
  }
  .btns {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 32px;
    .cancel {
      width: 180px;
      height: 48px;
      background: rgba(25, 30, 40, 0.08);
      border-radius: 8px 8px 8px 8px;
      color: #191e28;
      font-size: 16px;
    }
    .agree {
      width: 180px;
      height: 48px;
      background: #1dbf73;
      border-radius: 8px 8px 8px 8px;
      color: #fff;
      font-size: 16px;
    }
  }
}
</style>
<style>
.agreement .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: rgba(29, 191, 115, 1);
}
</style>
